package com.xiaobing.user.controller;

import com.xiaobing.common.base.BaseController;
import com.xiaobing.common.entity.system.SysDept;
import com.xiaobing.common.entity.system.SysRole;
import com.xiaobing.common.entity.system.SysUser;
import com.xiaobing.common.res.Result;
import com.xiaobing.common.utils.SecurityUtils;
import com.xiaobing.common.utils.StringUtils;
import com.xiaobing.user.service.ISysDeptService;
import com.xiaobing.user.service.ISysRoleService;
import com.xiaobing.user.service.ISysUserService;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 用户信息
 *
 * @author xulk
 */
@RestController
@RequestMapping("/user/user")
public class SysUserController extends BaseController {
    @Resource
    private ISysUserService userService;

    @Resource
    private ISysRoleService roleService;

    @Resource
    private ISysDeptService deptService; 

    /**
     * 获取用户列表
     */ 
    @GetMapping("/list")
    public Result list(SysUser user) { 
        List<SysUser> list = userService.selectUserList(user);
        return Result.success(list);
    }



    /**
     * 获取用户列表
     */
    @GetMapping("/page")
    public Result page(SysUser user) {
        return Result.success( userService.selectUserPage(user) );
    }
 
    /**
     * 根据用户编号获取详细信息
     */ 
    @GetMapping(value = {"/", "/{userId}"})
    public Result getInfo(@PathVariable(value = "userId", required = false) Long userId) {
        userService.checkUserDataScope(userId);
        Map<String, Object> map = new HashMap<>();
        List<SysRole> roles = roleService.selectRoleAll();
        map.put("roles", SysUser.isAdmin(userId) ? roles : roles.stream().filter(r -> !r.isAdmin()).collect(Collectors.toList()));
        if (StringUtils.isNotNull(userId)) {
            SysUser sysUser = userService.selectUserById(userId);
            map.put("roleIds", sysUser.getRoles().stream().map(SysRole::getId).collect(Collectors.toList()));
        }
        return Result.success(map);
    }

    /**
     * 新增用户
     */ 
    @PostMapping
    public Result add(@Validated @RequestBody SysUser user) {
        if (!userService.checkUserNameUnique(user)) {
            return error("新增用户'" + user.getUserName() + "'失败，登录账号已存在");
        } else if (StringUtils.isNotEmpty(user.getPhonenumber()) && !userService.checkPhoneUnique(user)) {
            return error("新增用户'" + user.getUserName() + "'失败，手机号码已存在");
        } else if (StringUtils.isNotEmpty(user.getEmail()) && !userService.checkEmailUnique(user)) {
            return error("新增用户'" + user.getUserName() + "'失败，邮箱账号已存在");
        }
//        user.setCreateBy(getUsername());
        user.setPassword(SecurityUtils.encryptPassword(user.getPassword()));
        return Result.success(userService.insertUser(user));
    }

    /**
     * 修改用户
     */ 
    @PutMapping
    public Result edit(@Validated @RequestBody SysUser user) {
        userService.checkUserAllowed(user);
        userService.checkUserDataScope(user.getId());
        if (!userService.checkUserNameUnique(user)) {
            return error("修改用户'" + user.getUserName() + "'失败，登录账号已存在");
        } else if (StringUtils.isNotEmpty(user.getPhonenumber()) && !userService.checkPhoneUnique(user)) {
            return error("修改用户'" + user.getUserName() + "'失败，手机号码已存在");
        } else if (StringUtils.isNotEmpty(user.getEmail()) && !userService.checkEmailUnique(user)) {
            return error("修改用户'" + user.getUserName() + "'失败，邮箱账号已存在");
        }
        user.setUpdateBy(getUsername());
        return Result.success(userService.updateUser(user));
    }

    /**
     * 删除用户
     */ 
    @DeleteMapping("/{userIds}")
    public Result remove(@PathVariable Long[] userIds) {
        if (ArrayUtils.contains(userIds, getUserId())) {
            return error("当前用户不能删除");
        }
        return Result.success(userService.deleteUserByIds(userIds));
    }

    /**
     * 重置密码
     */ 
    @PutMapping("/resetPwd")
    public Result resetPwd(@RequestBody SysUser user) {
        userService.checkUserAllowed(user);
        userService.checkUserDataScope(user.getId());
        user.setPassword(SecurityUtils.encryptPassword(user.getPassword()));
        user.setUpdateBy(getUsername());
        return Result.success(userService.resetPwd(user));
    }

    /**
     * 状态修改
     */ 
    @PutMapping("/changeStatus")
    public Result changeStatus(@RequestBody SysUser user) {
        userService.checkUserAllowed(user);
        userService.checkUserDataScope(user.getId());
        user.setUpdateBy(getUsername());
        return Result.success(userService.updateUserStatus(user));
    }

    /**
     * 根据用户编号获取授权角色
     */ 
    @GetMapping("/authRole/{userId}")
    public Result authRole(@PathVariable("userId") Long userId) {
        Map<String, Object> map = new HashMap<>();
        SysUser user = userService.selectUserById(userId);
        List<SysRole> roles = roleService.selectRolesByUserId(userId);
        map.put("user", user);
        map.put("roles", SysUser.isAdmin(userId) ? roles : roles.stream().filter(r -> !r.isAdmin()).collect(Collectors.toList()));
        return  Result.success(map);
    }

    /**
     * 用户授权角色
     */ 
    @PutMapping("/authRole")
    public Result insertAuthRole(Long userId, Long[] roleIds) {
        userService.checkUserDataScope(userId);
        userService.insertUserAuth(userId, roleIds);
        return  Result.success();
    }

    /**
     * 获取部门树列表
     */ 
    @GetMapping("/deptTree")
    public Result deptTree(SysDept dept) {
        return success(deptService.selectDeptToTree(dept));
    }
}
